<template>
  <div class="chart-container">
    <div class="year-selector">
      <el-select v-model="selectedYear" placeholder="请选择年份" @change="updateChart">
        <el-option v-for="year in yearList" :key="year" :label="year" :value="year" />
      </el-select>
    </div>
    <div ref="chartRef" style="width: 100%; height: calc(100% - 40px)"></div>
  </div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'
import { StatisticsApi } from '@/api/zszx/statistics/index'

const chartRef = ref<HTMLDivElement | null>(null)
let myChart: echarts.ECharts | null = null

// 年份选择相关
const selectedYear = ref(new Date().getFullYear())
const yearList = ref<number[]>([])
for (let year = 2024; year <= new Date().getFullYear(); year++) {
  yearList.value.push(year)
}

// 处理月份数据（填充缺失月份为0）
const processMonthlyData = (data: Array<{ month: number; [key: string]: any }>, key: string) => {
  const result = Array(12).fill(0)
  data.forEach(item => {
    if (item.month >= 1 && item.month <= 12) {
      result[item.month - 1] = item[key] || 0
    }
  })
  return result
}

// 更新图表数据
const updateChart = async () => {
  if (!chartRef.value) return
  
  try {
    const res = await StatisticsApi.monthlyStartEnd(selectedYear.value)
    
    // 处理三种数据
    const startData = processMonthlyData(res.monthlyStartCount, 'num')
    const endData = processMonthlyData(res.monthlyEndCount, 'num')
    const paidData = processMonthlyData(res.monthlyPaid, 'sum')
    
    // 初始化图表
    if (!myChart) {
      myChart = echarts.init(chartRef.value)
    }
    
      const option: EChartsOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params: any) => {
            const start = params[0].value
            const end = params[1].value
            const paid = params[2].value
            return `
              ${params[0].axisValue}<br/>
              <span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:#5470C6;"></span>新增生效: ${start}个<br/>
              <span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:#91CC75;"></span>到期合同: ${end}个<br/>
              <span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:#EE6666;"></span>交费金额: ¥${paid.toLocaleString()}
            `
          }
        },
        legend: {
          data: ['新增生效合同', '到期合同', '交费金额'],
          bottom: 0,
          itemGap: 20
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        yAxis: [
          {
            type: 'value',
            name: '合同数量',
            axisLabel: {
              formatter: '{value} 个'
            }
          },
          {
            type: 'value',
            name: '交费金额',
            axisLabel: {
              formatter: '¥{value}'
            }
          }
        ],
        series: [
          {
            name: '新增生效合同',
            type: 'bar',
            barGap: 0,
            emphasis: {
              focus: 'series'
            },
            data: startData,
            itemStyle: {
              color: '#5470C6'
            }
          },
          {
            name: '到期合同',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: endData,
            itemStyle: {
              color: '#91CC75'
            }
          },
          {
            name: '交费金额',
            type: 'bar',
            yAxisIndex: 1,
            data: paidData,
            itemStyle: {
              color: '#EE6666'
            }
          }
        ]
      }
    
    myChart.setOption(option)
  } catch (error) {
    console.error('获取月度统计数据失败:', error)
  }
}

onMounted(() => {
  updateChart()
  window.addEventListener('resize', () => {
    myChart?.resize()
  })
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', () => {
    myChart?.resize()
  })
  myChart?.dispose()
})
</script>

<style scoped>
.chart-container {
  display: flex;
  width: 100%;
  height: 100%;
  flex-direction: column;
}

.year-selector {
  display: flex;
  padding: 0 0 10px;
  align-items: center;
}
</style>
